import { TaHttp, TaPost } from '../script/ajax'
import { TaCache } from '../script/tools'
import { ShowStyle } from '../script/style'

// 基础数据接口
export const TaDataBase = {

	// 清理缓存数据
	clear() {
		TaCache.del('mall.regions')
		TaCache.del('mall.layout.pages')
		TaCache.del('mall.layout.navbar')
	},

	// 设置指定页面配置
	page(type: string, render: boolean = false): Promise<any> {
		return new Promise(async (resolve, reject) => {
			let pages = TaCache.get('mall.layout.pages') || []
			if (pages.length > 0) return findPage(pages)
			findPage((await this.layout().catch(reject)).layout.pages || [])

			function findPage(pages: any[], page: any = {}): any {
				pages.some((p: any) => (p.type === type ? (page = p) : null))
				if (render && page.head.name) uni.setNavigationBarTitle({ title: page.head.name });
				if (render && page.head) uni.setNavigationBarColor({
					animation: { duration: 400, timingFunc: 'easeIn' },
					frontColor: page.head.style.color.toLowerCase(),
					backgroundColor: page.head.style.backgroundColor.toLowerCase(),
					complete() { }
				})
				if (page.items) page.items.forEach((item: any) => {
					item._fontStyle = ShowStyle(item.fontStyle || {})
					item._outerStyle = ShowStyle(item.outerStyle || {})
					item._interStyle = ShowStyle(item.interStyle || {})
					item._inputStyle = ShowStyle(item.inputStyle || {})
				})
				resolve(page);
			}
		});
	},

	// 加载页面配置
	layout(): Promise<any> {
		TaCache.del('mall.layout.pages')
		TaCache.del('mall.layout.navbar')
		return new Promise((resolve, reject) => {
			TaHttp.get('/shop/api.data/layout').then((ret: any) => {
				if (ret.code === 1) {
					TaCache.set('mall.layout.pages', ret.data.layout.pages)
					TaCache.set('mall.layout.navbar', ret.data.layout.navbar)
					resolve(ret.data)
				} else {
					reject(ret)
				}
			})
		})
	},
	// 解析位置信息
	getAddressInfo(lng: string,lat:string) {
		return TaPost('/takeout/api.tencen/getGeo', { lng: lng, lat: lat })
	},
	// 获取配送区域
	region(): Promise<any> {
		return new Promise((resolve, reject) => {
			let data: any = TaCache.get('mall.regions') || []
			if (data.length > 0) return resolve(data)
			TaHttp.get('/plugin-wemall/api.goods/region').then((ret: any) => {
				if (ret.code === 1) {
					let data: any = []
					ret.data.map((x1: any) => {
						let subs1: any = []
						let item1: any = { label: x1.name, value: x1.name, children: subs1 }
						x1.subs.map((x2: any) => {
							let subs2: any = []
							let item2: any = { label: x2.name, value: x2.name, children: subs2 }
							x2.subs.map((x3: any) => subs2.push({ label: x3.name, value: x3.name })) && subs1.push(item2)
						}) && data.push(item1)
					})
					TaCache.set('mall.regions', data)
					resolve(data)
				} else {
					reject(ret)
				}
			}).catch(reject)
		})
	},

	// 获取用户协议
	agreement(): Promise<any> {
		return TaPost('/plugin-wemall/api.data/agreement')
	}
}